<template>
  <div class="wrapper-scroll">
    <div class="menu">
      <ul>
        <li v-for="(item, index) in [...menu, ...dynamicMenu]" :key="index" class="menu-item" @click="handleClick(index)">
          <el-button type="text" :class="getCurrentIndex() == index ? '' : 'el_button_text'">
            <strong>{{ item.label }}</strong>
          </el-button>
        </li>
      </ul>
    </div>
    <div class="wrapper-content">
      <ul class="wrapper-ul">
        <li class="content-item">
          <base-info ref="baseInfoRef" :is-disabled="isDisabled" class="baseInfo" :goods-info="goodsInfo" />
          <goodsAttribute
            ref="attrRef"
            :is-disabled="isDisabled"
            :goods-info="goodsInfo"
            class="goods-attribute"
            :channel-attribute-list="skuChannelInfos.Channel1"
          />
        </li>
        <li class="content-item">
          <goodsPhoto ref="goodsPhotoRef" :is-disabled="isDisabled" :goods-photos="goodsPhotos" :build-standard="buildStandard" />
        </li>
        <li class="content-item">
          <detailPage :id="$route.query.id" ref="detailPageRef" :is-disabled="isDisabled" :goods-info="goodsInfo" :build-standard="buildStandard" />
        </li>
        <li v-for="(item, index) in skuChannelInfos.Channel2" :key="index" class="content-item">
          <storeInfo :ref="'storeInfo' + index" :is-disabled="isDisabled" :commodity-attribute="item" :gutter="0" />
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
import BScroll from 'better-scroll'
import baseInfo from '@/views/coi/making/baseInfo.vue'
import goodsAttribute from '@/views/coi/making/goodsAttribute.vue'
import goodsPhoto from '@/views/coi/making/goodsPhoto.vue'
import detailPage from '@/views/coi/making/detailPage.vue'
import storeInfo from '@/views/coi/making/storeInfo.vue'

import { findSkuBuildInfoBySkuId } from '@/api/coi/onlineTaskAPI/sku'
export default {
  name: 'MenuScroll',
  components: {
    baseInfo,
    goodsAttribute,
    goodsPhoto,
    storeInfo,
    detailPage
  },
  data() {
    return {
      isDisabled: this.$route.query.type !== 'edit',
      contentScroll: null,
      listHeight: [], // 用来存储每一个子盒子的高度
      currentIndex: 0,
      scrollY: 0,
      buildStandard: 0,
      goodsPhotos: {
        skuOptionResources: [],
        transparentImg: [],
        skuResourcesImg: []
      },
      goodsInfo: {
        skuContentResources: [],
        skuContent: {
          content: ''
        },
        skuChannelInfos: []
      },
      menu: [
        {
          label: '商品信息',
          id: 0
        },
        {
          label: '商品图片',
          id: 1
        },
        {
          label: '商品详情',
          id: 2
        }
      ],
      dynamicMenu: []
    }
  },
  computed: {
    skuChannelInfos() {
      const Channel1 = this.goodsInfo.skuChannelInfos.filter(
        (item) => item.channelCode === '0' && Array.isArray(item.channelAttributeList && item.channelAttributeList.length)
      ) // 渠道商品属性
      const Channel2 = this.goodsInfo.skuChannelInfos.filter((item) => item.channelCode !== '0') // 类目属性
      return { Channel1, Channel2 }
    }
  },
  created() {
    this.queryData()
  },
  beforeDestroy() {
    if (this.contentScroll) this.contentScroll.destroy()
  },

  methods: {
    refreshScroll() {
      const _this = this
      const resizeObserver = new ResizeObserver((entries) => {
        _this.contentScroll && _this.contentScroll.refresh && _this.contentScroll.refresh()
        this.getHeightList()
      })
      resizeObserver.observe(document.querySelector('.wrapper-ul'))
    },
    // 路由跳转(补充渠道信息)
    goAddInformation(idList, type) {
      const query = {
        idList,
        type
      }
      this.$router.push({
        path: '/VendoraddInformation_Vendor',
        query
      })
    },
    async queryData() {
      try {
        this.$emit('changeLoading', true)
        const id = this.$route.query.id
        // const res = await categoryCheck({id})
        // if(!this.isDisabled) if(!res.result) return this.goAddInformation(id.toString(),'self')
        const { result } = await findSkuBuildInfoBySkuId(id)
        if (result) {
          this.goodsInfo = result
          this.$emit('getGoodTypeBoolean', result.goodsType)
          this.$emit('getGoodType', Boolean(result.goodsType === 'DROPSHIPPING' && result.yjdfLoadResult !== 1))
          this.buildStandard = result.buildStandard
          const i = result.skuChannelInfos.findIndex((item) => item.channelCode === '0')
          const item = result.skuChannelInfos.splice(i, 1)
          result.skuChannelInfos = item.concat(result.skuChannelInfos)
          result.skuChannelInfos.forEach((item, index) => {
            if (item.channelName) this.dynamicMenu.push({ label: item.channelName, id: index + 3 - 0 })
            // skuEditFlag个位
            item.channelAttributeList = item.channelAttributeList.filter((_) => {
              return parseInt(_.skuEditFlag.toString().charAt(_.skuEditFlag.toString().length - 1)) === 1
            })
            if (item.skuChannelInfo) {
              const data = JSON.parse(item.skuChannelInfo)
              if (item.channelAttributeList.length && data.channelAttributeList && Array.isArray(data.channelAttributeList)) {
                item.channelAttributeList.forEach((channelAttribute) => {
                  const index = data.channelAttributeList.findIndex((dataChannelAttribute) => dataChannelAttribute.attrId === channelAttribute.attrId)
                  if (index !== -1) channelAttribute.attrValue = data.channelAttributeList[index].attrValue
                  if (channelAttribute.sign && !channelAttribute.attrValue && this.goodsInfo[channelAttribute.sign]) {
                    channelAttribute.attrValue = this.goodsInfo[channelAttribute.sign]
                  }
                })
              }

              if (item.categoryAttributeList.length && data.categoryAttributeList && Array.isArray(data.categoryAttributeList)) {
                item.categoryAttributeList.forEach((categoryAttribute) => {
                  const index = data.categoryAttributeList.findIndex((dataCategoryAttribute) => dataCategoryAttribute.attrId === categoryAttribute.attrId)
                  if (index !== -1) {
                    categoryAttribute.attrValue = data.categoryAttributeList[index].attrValue
                    if ('unitValue' in data.categoryAttributeList[index]) categoryAttribute.unitValue = data.categoryAttributeList[index].unitValue
                  }
                })
              }
              item.skuChannelInfo = null
            } else {
              if (item.channelAttributeList.length) {
                item.channelAttributeList.forEach((channelAttribute) => {
                  if (channelAttribute.sign && !channelAttribute.attrValue && this.goodsInfo[channelAttribute.sign]) {
                    channelAttribute.attrValue = this.goodsInfo[channelAttribute.sign]
                  }
                })
              }
            }
          })
          // 过滤分类照片
          this.goodsPhotos.skuOptionResources = result.skuOptionResources // 素材图
          this.goodsPhotos.transparentImg = result.skuResources.filter((item) => item.resourceType === 3) // 透明
          this.goodsPhotos.skuResourcesImg = result.skuResources.filter((item) => item.resourceType === 1) // 主图
        }
      } finally {
        this.$emit('changeLoading', false)
        this.$nextTick(() => {
          this.getHeightList()
          this.initScroll()
        })
      }
    },

    initScroll() {
      const content = document.querySelector('.wrapper-content')
      this.contentScroll = new BScroll(content, {
        click: true, // 因为betterscroll默认会阻止点击事件。这里要设置一下
        mouseWheel: true, // 鼠标滚轮滚动
        probeType: 3,
        scrollY: true,
        scrollbar: {
          fade: false, // 是否显示滚动条
          interactive: false // 1.8.0 新增
        },
        preventDefault: true, // 阻止了浏览器默认选中行为
        preventDefaultException: { className: /^elImg$/, tagName: /^(INPUT|TEXTAREA|BUTTON|SELECT|AUDIO|IMG)$/ },
        tagException: { className: /^elImg$/, tagName: /^IMG$/ }
      })
      this.refreshScroll()
      // 获取滚动的值，赋值给scrollY
      this.contentScroll.on('scroll', (pos) => {
        this.scrollY = Math.abs(Math.round(pos.y))
      })
    },
    getCurrentIndex() {
      for (let i = 0; i < this.listHeight.length; i++) {
        const height = this.listHeight[i]
        const height1 = this.listHeight[i + 1]
        // 解决当滚动到最后时，内容不足盒子高度时，菜单显示问题。当滚动到最后，选中最后一个菜单
        // maxScrollY：最大纵向滚动位置
        if (Math.abs(this.contentScroll.maxScrollY) === Math.abs(this.scrollY)) {
          return [...this.menu, ...this.dynamicMenu].length - 1
        }
        if (!height1 || (this.scrollY < height1 && this.scrollY >= height)) {
          return i
        }
      }
    },
    handleClick(index) {
      const content = document.querySelector('.wrapper-content')
      const contentList = content.getElementsByClassName('content-item')
      const el = contentList[index]
      // scrollToElement：滚动到目标元素
      this.contentScroll.scrollToElement(el, 300)
    },
    getHeightList() {
      this.listHeight = []
      let height = 0
      this.listHeight.push(height)
      const content = document.querySelector('.wrapper-content')
      if (!content) return
      const contentList = content.getElementsByClassName('content-item') || []
      for (let i = 0; i < contentList.length; i++) {
        const item = contentList[i]
        height += item.clientHeight
        this.listHeight.push(height)
      }
    }
  }
}
</script>

<style scoped lang="scss">
.wrapper-scroll {
  height: 100%;
  overflow: hidden;
  margin: 0 auto;
}
.menu {
  // height: 100%;
  ul {
    display: flex;
    li {
      margin-right: 15px;
      list-style: none;
    }
  }
}
.wrapper-content {
  flex: 1;
  height: calc(100% - 70px);
  overflow: hidden;
  position: relative;
}
.active {
  border-color: #409eff;
  background: #409eff;
  color: #fff;
}
.content-item {
  &:first-child {
    padding-bottom: 0;
  }
  &:last-child {
    border-bottom: none;
  }
  padding: 20px 0;
  margin-right: 20px;
  border-bottom: 1px dashed #d9d9d9;
  .baseInfo {
    border-bottom: 1px dashed #d9d9d9;
    margin-bottom: 20px;
  }
}
.el_button_text {
  color: #606266;
}
/deep/ .el-input.is-disabled .el-input__inner {
  color: #666;
}

/deep/ .el-form-item__label::before {
  content: '*';
  margin-right: 4px;
  color: #fff;
}
ul > li {
  list-style: none;
}
.goods-attribute /deep/ .el-form-item,
.baseInfo /deep/ .el-form-item,
.storeInfo /deep/ .el-form-item,
/deep/ .special {
  max-width: 450px;
}
/deep/ .special {
  margin-top: 10px;
  display: flex;
  align-items: center;
  .el-form-item__content {
    flex: 1;
    display: flex;
    justify-content: flex-start;
    align-items: center;
  }
}
</style>
